package com.hqj.service;

import com.hqj.dao.FilesDao;
import com.hqj.entity.Files;
import com.hqj.util.FileUtil;
import com.hqj.util.ReturnValueUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class FileServiceI implements BaseService<Files>{

    @Autowired
    private FilesDao fd;

    @Value("${hqj.filePath}")
    private String filePath;

    public Map<String,Object> uploadFile(MultipartFile file,String tabName,String tabId){
        Map<String,Object> map = new HashMap<>();
        if(file!=null){

            //获取文件名
            String oldFileName = file.getOriginalFilename();//包含后缀名
            String newFileName = System.currentTimeMillis()+oldFileName.substring(oldFileName.lastIndexOf("."));
            File f1 = new File(filePath);
            FileUtil.createDir(f1);
            File f2 = new File(f1,newFileName);
            FileUtil.createFile(f2);
            try {
                //文件保存
                file.transferTo(f2);
                Files files = new Files();
                files.setTabName(tabName);
                files.setTabId(tabId);
                files.setOldFilename(oldFileName);
                files.setNewFilename(newFileName);
                files.setFileSize((int)file.getSize());
                files.setFilePath(f2.getAbsolutePath());
                map = this.add(files);
            }catch (Exception e){
                e.printStackTrace();
            }

        }
        return map;
    }

    @Override
    public List<Files> find(Files files) {
        List<Files> list = fd.find(files);
        for(Files file:list){
            String oldFileName = file.getOldFilename();
            String suffix = oldFileName.substring(oldFileName.lastIndexOf(".")+1);
            file.setStrDate(suffix);
        }
        return list;
    }

    @Override
    public Files get(Files files) {
        List<Files> list = fd.find(files);
        return list.size()>0?list.get(0):null;
    }

    @Override
    public Map<String, Object> add(Files files) {
        int i = fd.add(files);
        return ReturnValueUtil.aer(i,"新增");
    }

    @Override
    public Map<String, Object> edit(Files files) {
        return null;
    }

    @Override
    public Map<String, Object> remove(int id) {
        return null;
    }
}
